import { computed, defineComponent } from "vue";
import StringFiled from "./fields/StringFiled";
import NumberFiled from "./fields/NumberFiled";
import ObjectFiled from "./fields/ObjectField";
import ArrayFiled from "./fields/ArrayFiled";
import { SchemaTypes, FieldPropsDefine } from "./types";

import { retrieveSchema } from "./utils";
import { useVJSFContext } from "./context";

export default defineComponent({
  name: "SchemaItem",
  props: FieldPropsDefine,
  setup(props) {
    const formContext = useVJSFContext();

    const retrievedSchemaRef = computed(() => {
      const { schema, rootSchema, value } = props;
      return formContext.transformSchemaRef.value(
        retrieveSchema(schema, rootSchema, value)
      );
    });
    return () => {
      const { schema } = props;

      const retrievedSchema = retrievedSchemaRef.value;

      const type = schema?.type;

      let Component: any;

      switch (type) {
        case SchemaTypes.STRING: {
          Component = StringFiled;
          break;
        }
        case SchemaTypes.NUMBER: {
          Component = NumberFiled;
          break;
        }
        case SchemaTypes.OBJECT: {
          Component = ObjectFiled;
          break;
        }
        case SchemaTypes.ARRAY: {
          Component = ArrayFiled;
          break;
        }
        default: {
          console.warn(`${type} is not supported`);
        }
      }
      return <Component {...props} schema={retrievedSchema} />;
    };
  },
});
